<script>
  init({
    title: 'Issue #917',
    desc: 'Maintain selected on server side.(<a href="https://github.com/wenzhixin/bootstrap-table/issues/917" target="_blank">#917</a>).',
    links: ['bootstrap-table.min.css'],
    scripts: [
      'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js',
      'bootstrap-table.min.js'
    ]
  })
</script>

<table
  id="table"
  data-toggle="table"
  data-pagination="true"
  data-side-pagination="server"
  data-url="https://examples.wenzhixin.net.cn/examples/bootstrap_table/data"
  data-response-handler="responseHandler">
  <thead>
    <tr>
      <th data-field="state" data-checkbox="true"></th>
      <th data-field="id">ID</th>
      <th data-field="name">Item Name</th>
      <th data-field="price">Item Price</th>
    </tr>
  </thead>
</table>

<script>
  var $table = $('#table')
  var selections = []

  function responseHandler(res) {
    $.each(res.rows, function (i, row) {
      row.state = $.inArray(row.id, selections) !== -1
    })
    return res
  }

  function mounted() {
    $table.on('check.bs.table check-all.bs.table uncheck.bs.table uncheck-all.bs.table',
      function (e, rowsAfter, rowsBefore) {
        var rows = rowsAfter

        if (e.type === 'uncheck-all') {
          rows = rowsBefore
        }

        var ids = $.map(!$.isArray(rows) ? [rows] : rows, function (row) {
          return row.id
        })

        var func = $.inArray(e.type, ['check', 'check-all']) > -1 ? 'union' : 'difference'
        selections = window._[func](selections, ids)
      })
  }
</script>
